const http = require('http')
const fs = require('fs')
const archiver = require('archiver')
const child_process = require('child_process')
const querystring = require('querystring')

//1. 打开https://github.com/login/oauth/authorize

const auth_url = 'https://github.com/login/oauth/authorize'
const client_id = 'Iv1.d1f4d22e7103febe'
const app_id = '125537'

child_process.exec(`chromium ${auth_url}?client_id=${client_id}`)

//3. 创建server，接受token，然后点击发布
http.createServer(function(request, response) {
    let query = querystring.parse(request.url.match(/^\/\?([\s\S]+)$/)[1])
    console.log(query)
    publish(query.token)
}).listen(8083)

function publish(token) {
    let request = http.request({
        hostname: '127.0.0.1',
        port: '8082',
        method: 'POST',
        path: '/publish?token=' + token,
        headers: {
            'Content-Type': 'application/octet-stream'
        }
    }, response => {
        console.log(response)
    })

    const archive = archiver('zip', {
        zlib: { level: 9 }
    })
    archive.directory('./sample', false)
    archive.finalize()
    archive.pipe(request)
}
/*
 * 单个文件上传的代码。
let file = fs.createReadStream('./sample.html')
file.pipe(request)
file.on('end', () => {
    request.end()
})
*/
/*
 * 使用pipe后，就不再需要下面的事件代码了。
file.on('data', chunk => {
    console.log(chunk.toString())
    request.write(chunk)
})
file.on('end', chunk => {
    console.log('read finished.')
    request.end(chunk)
})
*/
